package br.com.iplant.mb;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSplitPane;

import java.awt.BorderLayout;

import javax.swing.JTree;
import javax.swing.JPanel;

import java.awt.CardLayout;
import java.util.List;

import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;


import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;

import br.com.iplant.dao.SafraDAO;
import br.com.iplant.vo.Safra;

public class Principal extends JFrame{
	private CadastroCultura cs = new CadastroCultura();
	private CadastroPropriedades cadastroPropriedades = new CadastroPropriedades();
	private CadastroSafra cadastroSafra = new CadastroSafra();
	private JSplitPane splitPane;
	private JTree tree;
	private SafraDAO safraDAO = new SafraDAO();
	private JPanel panel = new JPanel(new CardLayout(0, 0));
	private JPanel root = new JPanel();
	private CardLayout cardLayout = (CardLayout) panel.getLayout();
	private Safra safra = new Safra();
	public Principal() {
		setSize(600, 400);
		setDefaultCloseOperation(Principal.EXIT_ON_CLOSE);
		setLocationRelativeTo(this);
		getContentPane().setBackground(new Color(0, 128, 128));
		getContentPane().setLayout(new BorderLayout(0, 0));
		
		splitPane = new JSplitPane();
		getContentPane().add(splitPane);
		
		tree = new JTree();
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				
				TreePath treePath=e.getNewLeadSelectionPath();
				DefaultMutableTreeNode node =
				         (DefaultMutableTreeNode)treePath.getLastPathComponent();
				safra =(Safra) node.getUserObject();
				
				cadastroSafra.addSafra(safra);
				cardLayout.show(panel,"cadastroSafra");
				
			//	System.out.println(e.getNewLeadSelectionPath());
			}
		});
		
		iniciaArqore();
		
		splitPane.setLeftComponent(tree);
		
		
		
		
	
		
		panel.add(root, "root");
		panel.add(cadastroPropriedades, "cadastroPropriedades");
		panel.add(cadastroSafra, "cadastroSafra");
		
		splitPane.setRightComponent(panel);

	}
	 
	
	
	public void iniciaArqore(){
		tree.setModel(new DefaultTreeModel(
				new DefaultMutableTreeNode("Empresa") {
					{
						List<Safra> safras = safraDAO.getTodasAsSafras();
						for(Safra safra : safras){
							criaNodoSafra(this, safra);
						}
					}
				}
			));
	}
	
	public void criaNodoSafra(DefaultMutableTreeNode nodePai, Safra safra){
		DefaultMutableTreeNode node = new DefaultMutableTreeNode(safra);
		
		nodePai.add(node);
	}

	public static void main(String[] args) {
		new Principal().setVisible(true);
	}
}